package com.navi.util;

import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.navi.constant.GenericDef.PRINT_PROCESS_COST;
import static com.navi.constant.GenericDef.PRINT_PROCESS_COST_PERFORMANCE;

/**
 * Created by admin on 2017/11/28.
 */
@Slf4j
public class LogUtil {
    private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String stackTraceToString(Exception excp) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        excp.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }

    public static void pringStackTrace(Exception excp) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        excp.printStackTrace(pw);
        pw.flush();
        sw.flush();
        log.error(sw.toString());
    }

    /**
     * 记录处理时间
     *
     * @param process   业务逻辑
     * @param keyword   queueName / TableName等
     * @param message
     * @param beginTime
     * @return
     */
    public static long printCost(String process, String keyword, String message, long beginTime) {
        final long endTime = System.currentTimeMillis();
        log.info("{}, process: {}, keyword: {}, {}, {} ms", PRINT_PROCESS_COST, process, keyword, message, (endTime - beginTime));
        return endTime;
    }

    /**
     * 打印性能
     * @param process
     * @param keyword
     * @param dataCount
     * @param beginTime
     * @return
     */
    public static long printPerformance(String process, String keyword, long dataCount,long beginTime) {
        final long endTime = System.currentTimeMillis();
        // time, process,keyword,dataCount,cost
        log.info("{},{},{},{},{},{}", PRINT_PROCESS_COST_PERFORMANCE, df.format(new Date()), process, keyword, dataCount, (endTime - beginTime));
        return endTime;
    }
}
